package com.syni.mdd.sjb.common.datatreaure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppServiceOrder;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppServices;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppSmsService;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserSms;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.mapper.DxshAppServiceOrderMapper;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.RequestParamUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.RpcResponseVo;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiPay.WxPayPrepayDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.PayRestService;
import com.syni.mdd.sjb.common.datatreaure.service.*;
import com.syni.mdd.sjb.common.datatreaure.config.pay.alipay.PayConfig;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultCode;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.index.DataVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.pay.PayRqVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

@Service
public class WechatPayServiceImpl implements WechatPayService {
    @Autowired
    @Qualifier("payConfig")
    PayConfig payConfig;

    @Autowired
    DxshAppServiceOrderService dxshAppServiceOrderService;

    @Autowired
    DxshAppServiceOrderMapper dxshAppServiceOrderMapper;

    @Autowired
    DxshAppSmsServiceService dxshAppSmsServiceService;

    @Autowired
    DxshAppUserSmsService dxshAppUserSmsService;

    @Autowired
    DxshAppServicesService dxshAppServicesService;

    @Autowired
    PayRestService payRestService;


    private Logger log = LoggerFactory.getLogger(WechatPayServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appWechatPayNotify() {
        HttpServletRequest request = RequestParamUtils.getRequest();
        Map<String,String> forWardPayData = RequestParamUtils.getWxPayData(request);
        System.out.println("forWardPayData:"+forWardPayData);

        String orderNo = forWardPayData.get("out_trade_no");
        String transaction_id = forWardPayData.get("transaction_id");
        log.info(orderNo +" 用户已付款：.................................." +transaction_id );
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppServiceOrder.ORDER_NO,orderNo);
        DxshAppServiceOrder dxshAppServiceOrder = dxshAppServiceOrderService.getOne(queryWrapper);
        if(dxshAppServiceOrder.getStatus() == DxshAppServiceOrderService.NO_PAY_STATUS){
            //处理订单业务逻辑
            switch(dxshAppServiceOrder.getOrderType()){
                case DxshAppServiceOrderService.addedType :
                    //增值服务类型
                    queryWrapper.clear();
                    queryWrapper.eq(DxshAppServices.ID,dxshAppServiceOrder.getServiceId());
                    DxshAppServices dxshAppServices = dxshAppServicesService.getOne(queryWrapper);
                    if(dxshAppServices != null){
                        dxshAppServices.setBuyNum(dxshAppServices.getBuyNum()+1);
                        dxshAppServicesService.saveOrUpdate(dxshAppServices);
                    }
                    break;
                case DxshAppServiceOrderService.smsType:
                    //短信类型
                    queryWrapper.clear();
                    queryWrapper.eq(DxshAppSmsService.ID,dxshAppServiceOrder.getServiceId());
                    DxshAppSmsService dxshAppSmsService = dxshAppSmsServiceService.getOne(queryWrapper);
                    queryWrapper.clear();
                    queryWrapper.eq(DxshAppUserSms.USER_ID,dxshAppServiceOrder.getBmsUserId());

                    DxshAppUserSms dxshAppUserSms = dxshAppUserSmsService.getOne(queryWrapper);
                    if(dxshAppSmsService != null && dxshAppUserSms != null){
                        dxshAppUserSms.setSmsNum(dxshAppUserSms.getSmsNum()+dxshAppSmsService.getNumber());
                        dxshAppUserSmsService.saveOrUpdate(dxshAppUserSms);
                        log.info(String.format("短信充值执行成功  userid:%s,充值数量:%s",dxshAppServiceOrder.getId(),dxshAppSmsService.getNumber()));

                    }

                    break;

                default:break;

            }

            //修改订单状态
            dxshAppServiceOrder.setTransactionId(transaction_id);
            dxshAppServiceOrder.setStatus(DxshAppServiceOrderService.PAY_STATUS);
            dxshAppServiceOrder.setPayStatus(DxshAppServiceOrderService.PAY_STATUS);
            dxshAppServiceOrder.setTalkStatus(Constants.COMMON_FLAG_FALSE_INT);
            dxshAppServiceOrder.setServeTime(LocalDateTime.now());
            dxshAppServiceOrder.setPayTime(LocalDateTime.now());
            dxshAppServiceOrder.setPayWay(2);

            dxshAppServiceOrderMapper.updateById(dxshAppServiceOrder);
            log.info(" ------------------>  充值/购买 回调完毕  <---------------------");
            log.info(dxshAppServiceOrder.toString());
        }
    }

    @Override
    public Map<String, Object> prepay(PayRqVo payRqVo) {
        DataVo dataVo = new DataVo();
        dataVo.setLocalDateTime(DateTimeUtils.converDateToLocalDateTime(new Date(0)));
        if(payRqVo.getIsCustomize() == Constants.COMMON_FLAG_TRUE_INT){
            WxPayPrepayDto wxPayPrepayDto = new WxPayPrepayDto();
            wxPayPrepayDto.setOrderNo(payRqVo.getOrderNo());
            wxPayPrepayDto.setBody("订单号：" + payRqVo.getOrderNo());
            wxPayPrepayDto.setAttach("默认");
            BigDecimal money = new BigDecimal(payRqVo.getTotalAmt());
            wxPayPrepayDto.setTotalAmt(String.valueOf(money.multiply(new BigDecimal(100.00)).intValue()));
            wxPayPrepayDto.setNotifyUrl(payRqVo.getNotifyUrl());
            RpcResponseVo rpcResponseVo = payRestService.wxPayPrepay(wxPayPrepayDto);
            if(rpcResponseVo.isSuccess()){
                Map<String,Object> data = (Map<String, Object>) rpcResponseVo.getData();
                return ResultMapHelper.success(data,ResultMsg.MSG_GET_SUCCESS);
            }
        }else{
            //检验订单号和订单id是否一致

            DxshAppServiceOrder dxshAppServiceOrder = dxshAppServiceOrderService.getOne(new QueryWrapper<DxshAppServiceOrder>().eq(DxshAppServiceOrder.ID,payRqVo.getOrderId()));
            if (dxshAppServiceOrder == null) {
                return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST, ResultMsg.CODE_ORDER_NO_EXIST);
            }
            if (!dxshAppServiceOrder.getOrderNo().equals(payRqVo.getOrderNo())) {
                return ResultMapHelper.result(ResultCode.CODE_ORDER_ID_NOMATCH_NO, ResultMsg.CODE_ORDER_ID_NOMATCH_NO);
            }
            if(!(dxshAppServiceOrder.getStatus() == Constants.COMMON_FLAG_FALSE_INT)){
                return ResultMapHelper.failure("非待支付状态");
            }



            WxPayPrepayDto wxPayPrepayDto = new WxPayPrepayDto();
            wxPayPrepayDto.setOrderNo(payRqVo.getOrderNo());
            wxPayPrepayDto.setBody("订单号：" + payRqVo.getOrderNo());
            wxPayPrepayDto.setAttach("默认");
            wxPayPrepayDto.setTotalAmt(String.valueOf(dxshAppServiceOrder.getTotalPrice().multiply(new BigDecimal(100.00)).intValue()));
            wxPayPrepayDto.setNotifyUrl(payConfig.getWxcallBackUrl());
            RpcResponseVo rpcResponseVo = payRestService.wxPayPrepay(wxPayPrepayDto);
            if(rpcResponseVo.isSuccess()){
                Map<String,Object> data = (Map<String, Object>) rpcResponseVo.getData();
                return ResultMapHelper.success(data,ResultMsg.MSG_GET_SUCCESS);
            }

        }
        return ResultMapHelper.success(dataVo,ResultMsg.MSG_GET_SUCCESS);

    }
}
